package data_cache

import (
	"errors"
	"sync"
)

type DataCache struct {
	cache *sync.Map
}

func NewDataCache() *DataCache {
	return &DataCache{cache: &sync.Map{}}
}

func (this *DataCache) check() error {
	if this.cache == nil {
		return errors.New("DataCache not init.")
	}
	return nil
}

func (this *DataCache) Get(key interface{}) (interface{}, error) {
	err := this.check()
	if err != nil {
		return nil, err
	}
	value, ok := this.cache.Load(key)
	if !ok {
		return nil, errors.New("cache.Load failed.")
	}
	return value, nil
}

func (this *DataCache) Set(key interface{}, value interface{}) error {
	err := this.check()
	if err != nil {
		return err
	}
	this.cache.Store(key, value)
	return nil
}

func (this *DataCache) Delete(key interface{}) error {
	err := this.check()
	if err != nil {
		return err
	}
	this.cache.Delete(key)
	return nil
}
